package com.dmjj.filter;

import com.alibaba.fastjson.JSON;
import com.dmjj.common.redisc.RedisUtil;
import com.dmjj.common.result.ResultEnum;
import com.dmjj.common.result.ResultObject;
import com.dmjj.common.util.PropertyUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

@Component
public class MyZuulFilter extends ZuulFilter {
    private static Logger log = LoggerFactory.getLogger(MyZuulFilter.class);

    @Autowired
    private ResultObject resultObject;

    @Autowired
    private PropertyUtil propertyUtil;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        HttpServletResponse response = ctx.getResponse();
        log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
        String url = request.getRequestURI();
        String token = null;
        String callbackparam = null;
        if(url.equals("/dmjjxt/brand/brandUpload")){
            return resultObject.success(ResultEnum.SUCCESS.getCode(), "访问成功");
        }
        if (url.indexOf("goDMJJLogin/confirmLogin")>-1){
            String param = request.getParameter("data");
            callbackparam = request.getParameter("callback");
            if (!param.isEmpty()){
                Map mapType = JSON.parseObject(param,Map.class);
                token = mapType.get("token")!=null?mapType.get("token").toString():null;
            }
        }else {
            token = request.getParameter("token")!=null?request.getParameter("token"):null;
        }
        String requestURL = request.getServletPath();
        if (propertyUtil.getAllowUrl() != null && propertyUtil.getAllowUrl().length > 0) {
            Pattern pattern = null;
            for (String au : propertyUtil.getAllowUrl()) {
                pattern = Pattern.compile(au);
                if (pattern.matcher(requestURL).find()) {
                    return null;
                }
            }
        }
        if(token == null) {
            String requesturl = request.getRequestURL().toString();
            //校验不需要token的url
            if (propertyUtil.getNoTokenUrl() != null && propertyUtil.getNoTokenUrl().length > 0) {
                Pattern pattern = null;
                for (String au : propertyUtil.getNoTokenUrl()) {
                    pattern = Pattern.compile(au);
                    if (pattern.matcher(requestURL).find()) {
                        return null;
                    }
                }
            }
            log.warn("token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                ctx.setSendZuulResponse(false);
                response.setContentType("text/html;charset=utf-8");
                if (callbackparam!=null &&!callbackparam.isEmpty()){
                    Map result = new HashMap();
                    result.put("code",1002);
                    result.put("msg","访问失败，请重新登陆");
                    String jsonData = JSON.toJSONString(result);
                    String retStr = callbackparam + "(" + jsonData + ")";
                    response.getWriter().print(retStr);
                }else {
                    response.getWriter().write("访问失败，请重新登陆");
                }
            }catch (Exception e){}
            return null;

        }else{
            Boolean IsExistToken = redisUtil.hasKey(token);
            if(IsExistToken&& redisUtil.get(token)!=null){
                System.out.println("#########################进入网关");
                return resultObject.success(ResultEnum.SUCCESS.getCode(), "访问成功");
            }else{
                try {
                    ctx.setSendZuulResponse(false);
                    response.setContentType("text/html;charset=utf-8");
                    if ( callbackparam!=null && !callbackparam.isEmpty()){
                        Map result = new HashMap();
                        result.put("code",1002);
                        result.put("msg","访问失败，请重新登陆");
                        String jsonData = JSON.toJSONString(result);
                        String retStr = callbackparam + "(" + jsonData + ")";
                        response.getWriter().print(retStr);
                    }else {
                        response.getWriter().write("访问失败，请重新登陆");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}
